package simplescenegraph.spaceshooter;

import simplescenegraph.LeafNode;
import simplescenegraph.math.Transform;
import simplescenegraph.math.Vector3f;

public class Spaceship {

	private static final float ROTATION_STEP = 10.0f;

	private static final float SPEED_DECAY_STEP = 0.0003f;
	
	private static final float ACCELERATION_STEP = 0.001f;

	private static final float MAXIMUM_ACCELERATION = 0.01f;
	
	private static final float MAXIMUM_SPEED = 0.05f;
	
	float acceleration = 0.0f;
	
	float speed = 0.0f;
	
	LeafNode node;

	float angle;

	public Spaceship(LeafNode node) {
		this.node = node;
	}

	public void rotateLeft() {
		angle -= ROTATION_STEP;
		node.rotateY(ROTATION_STEP);
	}

	public void rotateRight() {
		angle += ROTATION_STEP;
		node.rotateY(-ROTATION_STEP);
	}

	public void accelerate() {
		acceleration = Math.min(acceleration + ACCELERATION_STEP, MAXIMUM_ACCELERATION);
	}
	
	public void deaccelerate() {
		acceleration = Math.max(acceleration - ACCELERATION_STEP, -MAXIMUM_ACCELERATION);
	}
	
	public void move(float deltaTime) {
		Vector3f newPosition = new Vector3f(node.getPosition());
		
		newPosition.add(getVelocity(deltaTime));
		
		node.setPosition(newPosition);
	}

	protected Vector3f getVelocity(float deltaTime) {
		// V = Vo + a.t
		speed = Math.min(speed + (acceleration * deltaTime), MAXIMUM_SPEED);
		
		if (speed < 0) {
			speed = 0;
		}
		
		// From scalar to vectorial
		Vector3f velocity = new Vector3f(Vector3f.Y_AXIS);
		velocity.multiply(speed);
		Transform transform = new Transform();
		transform.rotateZ(angle);
		transform.transform(velocity);
		
		return velocity;
	}
	
	public void speedDecay(float deltaTime) {
		speed -= SPEED_DECAY_STEP * deltaTime;
		
		if (speed < 0) {
			speed = 0;
		}
	}

}
